<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <h1>
      bucket改为map形式{name:set(fn,fn,fn),age:set(fn,fn,fn)}
    </h1>
    <div id="app"></div>
    <script>
      const bucket = new Map();
      let activeEffect = null
      function isObject(obj) {
        return typeof obj === 'object' && obj !== null
      }
      function reactive(data) {
        if (!isObject(data)) return
        return new Proxy(data, {
          get(target, key) {
            if(activeEffect) {
              let depSet = bucket[key]
              if(!depSet) {
                depSet = new Set()
                bucket.set(key,depSet)
              }
              depSet.add(activeEffect)
            }
            return target[key]
          },
          set(target, key, value) {
            target[key] = value
            const depset = bucket.get(key)
            if(depset) {
              depset.forEach(fn => fn())
            }
            return true
          },
        })
      }

      function registerEffect(fn) {
        if(typeof fn !=='function') {
          return
        }
        activeEffect = fn
        fn()
        activeEffect = null
      }
      const obj = reactive({ name: '小胖', age: 30 })

      registerEffect(function () {
        console.log('副作用函数1')
        app.innerHTML = obj.name
      })
      registerEffect(function () {
        console.log('副作用函数2')
      })

      setTimeout(() => {
        obj.name = '小小胖'
      }, 2000)
    </script>
  </body>
</html>
